package com.finger.forest;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.finger.forest.adapter.UserManagerAdapter;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.GridUserModel;
import com.finger.forest.model.UserManagerModel;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.UniversalItemDecoration;
import com.jakewharton.rxbinding2.view.RxView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * 用户管理
 */
public class UserManagerActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    @BindView(R.id.tvAddUser)
    TextView tvAddUser;

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvEditInfo)
    TextView tvEditInfo;
    @BindView(R.id.tvRightTitle)
    TextView tvRightTitle;
    @BindView(R.id.tvSelectNum)
    TextView tvSelectNum;

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.rvUserManager)
    RecyclerView rvUserManager;

    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.llEdit)
    LinearLayout llEdit;
    @BindView(R.id.bnDelete)
    Button bnDelete;

    private List<GridUserModel> userManagerModels = new ArrayList<>();
    private List<GridUserModel> selectUserManagerModels = new ArrayList<>();

    private UserManagerAdapter userManagerAdapter;

    @Override
    protected int setView() {
        return R.layout.activity_user_manager;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        tvTitle.setText("用户管理");
        tvRightTitle.setVisibility(View.GONE);
        tvRightTitle.setText("取消");

        userManagerAdapter = new UserManagerAdapter(R.layout.user_manager_item_view, userManagerModels);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        rvUserManager.setLayoutManager(linearLayoutManager);
        rvUserManager.setAdapter(userManagerAdapter);

        rvUserManager.addItemDecoration(new UniversalItemDecoration() {
            @Override
            public Decoration getItemOffsets(int position) {
                ColorDecoration colorDecoration = new ColorDecoration();
                colorDecoration.bottom = getResources().getDimensionPixelOffset(R.dimen.dp_1);
                colorDecoration.decorationColor = ContextCompat.getColor(context, R.color.blackF5);
                return colorDecoration;
            }
        });

        userManagerAdapter.setOnUserManagerSelectListener(new UserManagerAdapter.OnUserManagerSelectListener() {
            @Override
            public void selectListener() {
                selectUserManagerModels.clear();
                for (GridUserModel userManagerModel : userManagerModels) {
                    if (userManagerModel.isSelect()) {
                        selectUserManagerModels.add(userManagerModel);
                    }
                }

                tvSelectNum.setText("已选择" + selectUserManagerModels.size() + "条");
            }
        });

        userManagerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GridUserModel userManagerModel = userManagerModels.get(position);
                if (null != userManagerModel) {
                    Intent intent = new Intent(context, AddNewUserActivity.class);
                    intent.putExtra("userManagerModel", userManagerModel);
                    startActivity(intent);
                }
            }
        });

        clicks();
    }

    private void clicks() {
        //新增用户
        RxView.clicks(tvAddUser).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            Intent intent = new Intent(this, AddNewUserActivity.class);
            startActivityForResult(intent, 0x001);
        });

        //返回
        RxView.clicks(ivLeft).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            finish();
        });

        //编辑信息
        RxView.clicks(tvEditInfo).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            tvRightTitle.setVisibility(View.VISIBLE);
            llEdit.setVisibility(View.VISIBLE);
            llBottom.setVisibility(View.GONE);

            for (GridUserModel managerModel : userManagerModels) {
                managerModel.setShow(true);
                managerModel.setSelect(false);
            }
            selectUserManagerModels.clear();
            tvSelectNum.setText("已选择" + selectUserManagerModels.size() + "条");
            userManagerAdapter.notifyDataSetChanged();
        });

        //编辑信息状态取消
        RxView.clicks(tvRightTitle).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            tvRightTitle.setVisibility(View.GONE);
            llEdit.setVisibility(View.GONE);
            llBottom.setVisibility(View.VISIBLE);

            for (GridUserModel managerModel : userManagerModels) {
                managerModel.setShow(false);
                managerModel.setSelect(false);
            }
            selectUserManagerModels.clear();
            tvSelectNum.setText("已选择" + selectUserManagerModels.size() + "条");
            userManagerAdapter.notifyDataSetChanged();
        });

        //删除用户
        RxView.clicks(bnDelete).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            if (selectUserManagerModels.size() == 0) {
                ToastUtils.show("请先选择需要删除的用户");
                return;
            }

            JSONArray jsonArray = new JSONArray();
            for (GridUserModel userManagerModel : selectUserManagerModels) {
                jsonArray.put(userManagerModel.getId());
            }

            showPd();
            Map<String, Object> maps = new HashMap<>();
            maps.put("userId", jsonArray);
            presenter.deleteUser(maps);
        });
    }

    @Override
    protected void loadDataFromServer() {
        loadUser();
    }

    private void loadUser() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId", drUid);
        showPd();
        presenter.loadUserManager(maps);
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            //用户列表
            case ResponseTag
                    .USER_MANAGER:
                List<GridUserModel> userManagerModelList = (List<GridUserModel>) model;
                if (null != userManagerModelList && userManagerModelList.size() > 0) {
                    userManagerModels.clear();
                    userManagerModels.addAll(userManagerModelList);

                    userManagerAdapter.notifyDataSetChanged();
                }
                break;

            //删除用户
            case ResponseTag.DELETE_USER:
                ToastUtils.show(msg);

                tvRightTitle.setVisibility(View.GONE);
                llEdit.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);

                for (GridUserModel managerModel : userManagerModels) {
                    managerModel.setShow(false);
                    managerModel.setSelect(false);
                }
                selectUserManagerModels.clear();
                tvSelectNum.setText("已选择" + selectUserManagerModels.size() + "条");
                userManagerAdapter.notifyDataSetChanged();

                loadUser();
                break;
        }

        hidePd();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        hidePd();
        ToastUtils.show(message == null ? "网络异常" : message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == 0x001) {
            loadUser();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}